import { Button, Card } from "antd";
import * as echarts from "echarts";
import { useEffect, useRef, useState } from "react";

const Line: React.FC = () => {
  // 表格所在的div的ref
  const contariner = useRef<any>(null);
  // 表格配置项options
  const [options] = useState({
    title: {
      text: "销售趋势",
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        label: {
          backgroundColor: "#6a7985",
        },
      },
    },
    legend: {
      data: ["电器", "书籍", "家具", "家居", "饰品"],
    },
    toolbox: {
      feature: {
        dataZoom: {
          yAxisIndex: "none",
        },
        restore: {},
        saveAsImage: {},
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: [
      {
        type: "category",
        boundaryGap: false,
        data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
      },
    ],
    yAxis: [
      {
        type: "value",
      },
    ],
    series: [
      {
        name: "电器",
        type: "line",
        stack: "Total",
        areaStyle: {},
        emphasis: {
          focus: "series",
        },
        data: [120, 132, 101, 134, 90, 230, 210],
      },
      {
        name: "书籍",
        type: "line",
        stack: "Total",
        areaStyle: {},
        emphasis: {
          focus: "series",
        },
        data: [220, 182, 191, 234, 290, 330, 310],
      },
      {
        name: "家具",
        type: "line",
        stack: "Total",
        areaStyle: {},
        emphasis: {
          focus: "series",
        },
        data: [150, 232, 201, 154, 190, 330, 410],
      },
      {
        name: "家居",
        type: "line",
        stack: "Total",
        areaStyle: {},
        emphasis: {
          focus: "series",
        },
        data: [320, 332, 301, 334, 390, 330, 320],
      },
      {
        name: "饰品",
        type: "line",
        stack: "Total",
        label: {
          show: true,
          position: "top",
        },
        areaStyle: {},
        emphasis: {
          focus: "series",
        },
        data: [820, 932, 901, 934, 1290, 1330, 1320],
      },
    ],
  });
  // 点击修改表格项options内容
  const update = () => {
    // 更新表格内容 先注销掉已有的表格 再重新初始化
    echarts.init(contariner.current).dispose();
    initCharts();
  };

  // 初始化表格的函数
  const initCharts = () => {
    const chart: any = echarts.init(contariner.current);
    chart.setOption(options);
  };

  // 页面加载时候初始化表格
  useEffect(() => {
    initCharts();
    // 表格初始化了
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div>
      <Card>
        <Button type="primary" onClick={update}>
          更新内容
        </Button>
      </Card>

      <Card title="折线图">
        <div
          ref={contariner}
          style={{ width: "1550px", height: "580px" }}
        ></div>
      </Card>
    </div>
  );
};

export default Line;
